﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace multi_task
{
    class Homework {
        private int id_;
        public Homework(int id) { id_ = id; }
        public int do_work() {
            string tid = Thread.CurrentThread.ManagedThreadId.ToString();
            System.Console.WriteLine("Begin Homework {0} at {1}",id_,tid);
            int count = id_;
            while (count-- > 0) {
                System.Threading.Thread.Sleep(500);
            }
            System.Console.WriteLine("End Homework {0}",id_);
            return id_;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Homework hw1 = new Homework(7);
            Homework hw2 = new Homework(8);
            Homework hw3 = new Homework(9);
            Homework hw4 = new Homework(100);

            // Create four background task.
            Task<int> task1 = new Task<int>(hw1.do_work);
            Task<int> task2 = new Task<int>(hw2.do_work);
            Task<int> task3 = new Task<int>(hw3.do_work);
            Task<int> task4 = new Task<int>(hw4.do_work);

            task1.Start();
            task2.Start();
            task3.Start();
            task4.Start();
            // Wait for task2.
            System.Console.WriteLine("Return value from task1 > {0}",task2.Result);
            // Wait for all of thread.
            Task.WaitAll(task1,task2,task3);

            System.Console.ReadKey();
        }
    }
}
